package com.iot.ammeter.view

import android.content.Intent
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.*
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.lifecycleScope
import com.iot.ammeter.IApplication
import com.iot.ammeter.R
import com.iot.ammeter.network.Repository
import com.iot.ammeter.ui.theme.AmmeterAppTheme
import com.iot.ammeter.ui.components.auth.Login
import com.iot.ammeter.ui.components.auth.Register
import kotlinx.coroutines.launch

/**
 * 授权页面：
 * - 登录后前往主页 [MainActivity]
 * - 注册后前往绑定页面 [DeviceBindActivity]
 */
class AuthActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            AuthScreen(
                login = ::loginLogic,
                register = ::registerLogic
            )
        }
    }

    /**
     * 登录逻辑
     */
    private fun loginLogic(email: String, password: String, onFinished: () -> Unit) =
        lifecycleScope.launch {
            // 当相关请求失败后，调用按钮完成逻辑，使按钮再次可用
            Repository.login(email, password, onFailure = onFinished) {
                IApplication.token = it
                withBaseInfo(it, MainActivity::class.java, onFinished)
            }
        }

    /**
     * 注册逻辑
     */
    private fun registerLogic(
        email: String,
        password: String,
        mailCode: String,
        onFinished: () -> Unit
    ) = lifecycleScope.launch {
        // 当相关请求失败后，调用按钮完成逻辑，使按钮再次可用
        Repository.register(email, password, mailCode, onFailure = onFinished) {
            IApplication.token = it
            withBaseInfo(it, DeviceBindActivity::class.java, onFinished)
        }
    }

    /**
     * 获取 token 后请求基本信息，完成请求后打开 [MainActivity]
     */
    private fun withBaseInfo(token: String, goto: Class<*>, onFailure: () -> Unit) =
        lifecycleScope.launch {
            Repository.getBaseInfo(
                token = token,
                onFailure = onFailure
            ) { userInfo, deviceInfo, lastMonthInfo ->
                IApplication.userInfo = userInfo
                IApplication.deviceInfo = deviceInfo
                IApplication.lastMonthInfo = lastMonthInfo
                startActivity(Intent(this@AuthActivity, goto))
                finish()
            }
        }
}

@Composable
private fun AuthScreen(
    login: (email: String, password: String, onFinished: () -> Unit) -> Unit,
    register: (email: String, password: String, mailCode: String, onFinished: () -> Unit) -> Unit
) = AmmeterAppTheme {
    var isLogin by remember { mutableStateOf(true) }
    Column(
        Modifier
            .padding(40.dp)
            .fillMaxWidth()
            .fillMaxHeight(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(
            text = stringResource(id = R.string.auth_title),
            textAlign = TextAlign.Center,
            color = MaterialTheme.colorScheme.primary,
            style = MaterialTheme.typography.headlineLarge,
            modifier = Modifier
                .fillMaxWidth()
                .padding(0.dp, 0.dp, 0.dp, 30.dp)
        )
        if (isLogin) Login(login)
        else Register(register)
        TextButton(onClick = { isLogin = !isLogin }, Modifier.padding(top = 10.dp)) {
            Text(
                color = MaterialTheme.colorScheme.primary,
                text = "前往" + stringResource(id = if (isLogin) R.string.register else R.string.login)
            )
        }
    }
}

@Preview(name = "wrap", showBackground = true)
@Preview(name = "wrap night", showBackground = true, uiMode = UI_MODE_NIGHT_YES)
@Composable
private fun EnterScreenPreview() = AuthScreen(
    login = { _, _, _ -> },
    register = { _, _, _, _ -> }
)

